package com.runtime.hongyunuser.service.Impl;

import com.runtime.hongyunuser.controller.PasswordUtil;
import com.runtime.hongyunuser.mapper.PasswordMapper;
import com.runtime.hongyunuser.service.PasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class PasswordServiceImpl implements PasswordService {
    @Autowired
    private PasswordMapper passwordMapper;

    @Override
    public boolean resetPassword(Long userId, String oldPassword, String newPassword) {
        if (userId == null || userId <= 0) return false;
        if (oldPassword == null || oldPassword.trim().isEmpty()) return false;
        if (newPassword == null || newPassword.length() < 8) return false;

        String storedCombined = passwordMapper.getOldPassword(userId);
        if (storedCombined == null) return false;

        String[] parts = PasswordUtil.splitSaltAndHash(storedCombined);
        if (parts.length != 2) return false;

        String salt = parts[0];
        String storedHash = parts[1];
        String inputHash = PasswordUtil.hashWithSalt(oldPassword, salt);

        if (!inputHash.equals(storedHash)) return false;

        String newSalt = PasswordUtil.generateSalt();
        String newHash = PasswordUtil.hashWithSalt(newPassword, newSalt);
        String newCombined = PasswordUtil.combineSaltAndHash(newSalt, newHash);

        return passwordMapper.reset(userId, newCombined) > 0;
    }
}